/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.async;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.widget.Toast;

import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.android.widgets.view.CrossableItem;
import com.phonebooksharing.dto.ReturnItem;

@SuppressWarnings("unchecked")
public class ManageSharingTask extends NetworkHandlerTask<Void, Void, ReturnItem> {
    private ProgressDialog pd;
    protected Context cx;
    protected ArrayList<CrossableItem> checkList;
    private String sharingType;
    public ManageSharingTask(Context cx, ArrayList<CrossableItem> checkList, String sharingType) {
        this.cx = cx;
        this.checkList = checkList;
        this.sharingType = sharingType;
    }
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(cx);
        pd.setMessage("Please wait while processing your request...");
        pd.setCancelable(false);
        pd.show();
    }

    @Override
    protected ReturnItem doInBackground(Void... params) {
        ReturnItem ri = null;
        try {
            ArrayList<CrossableItem> cl = checkList;
            ArrayList list = new ArrayList();
            for (CrossableItem<?> ci : cl) {
                list.add(ci.item);
            }
            
            final String url = String.format(Global.PROFILE_SERVLET_URL, "ms" /*ac*/, sharingType /*q*/);
            ri = (ReturnItem)doNetworkPost(url, list);

            publishProgress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ri;
    }

    @Override
    protected void onPostExecute(ReturnItem result) {
        super.onPostExecute(result);
        pd.dismiss();
        if(!result.isOK()) {
            Toast.makeText(cx, "It was not possible to proceed with your request, please try it later again.", Toast.LENGTH_LONG).show();
        }
    }
}
